package com.ztesoft.sca.controller.user;

import com.google.gson.Gson;
import com.ztesoft.sca.common.Constants;
import com.ztesoft.sca.model.user.ImPrivilegePo;
import com.ztesoft.sca.model.user.ImUserPo;
import com.ztesoft.sca.service.user.ImUserService;
import com.ztesoft.sca.util.exception.ExceptionUtil;
import com.ztesoft.sca.util.json.GsonUtils;
import com.ztesoft.sca.util.message.ResponseUtils;
import com.ztesoft.sca.util.seq.SequenceCreator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.Request;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liang.aozhao
 * @created 2018/5/15 20:22
 */
@RestController
@RequestMapping("/api/user")
public class ImUserController {

    private static final Logger logger = LoggerFactory.getLogger(ImUserController.class);

    @Autowired
    ImUserService imUserService;

    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    public String addUser(@RequestBody ImUserPo imUserPo) {
        if (logger.isDebugEnabled()) {
            logger.debug(imUserPo.toString());
        }
        long userId;
        try {
            userId = SequenceCreator.getSequence("IM_USER_SEQ");
            imUserPo.setUserId(userId);
            imUserService.addImUser(imUserPo);
        } catch (Exception e) {
            logger.error("新增用户失败!", e);
            return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
        }
        logger.info("新增用户,userId为" + userId);
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC, Constants.INF_DESC_SUCC, userId);
    }

    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    public String deleteUser(@RequestBody ImUserPo imUserPo) {
        Long userId = imUserPo.getUserId();
        logger.info("将删除用户id：" + userId);
        try {
            if (userId != null) {
                imUserService.deleteImUser(imUserPo);
            }
        } catch (Exception e) {
            logger.error("删除用户失败!", e);
            return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
        }
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC, Constants.INF_DESC_SUCC, null);
    }

    @RequestMapping(value = "/update", method = {RequestMethod.PUT,RequestMethod.POST})
    public String updateUser(@RequestBody ImUserPo imUserPo) {
        if (logger.isDebugEnabled()) {
            logger.debug(imUserPo.toString());
        }
        try {
            Long userId = imUserPo.getUserId();
            logger.info("将更新的用户Id:" + userId);
            if (userId != null) {
                //已限制不能修改注册时间
                imUserService.updateImUser(imUserPo);
            }
        } catch (Exception e) {
            logger.error("更新用户信息失败", e);
            return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
        }
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC, Constants.INF_DESC_SUCC, null);
    }

    @RequestMapping(value = "/getImUser", method = {RequestMethod.POST})
    public String getImUser(@RequestBody ImUserPo imUserPo) {
        if (logger.isDebugEnabled()) {
            logger.debug(imUserPo.toString());
        }
        ImUserPo imUser = null;
        try {
            imUser = imUserService.getImUser(imUserPo);
        } catch (Exception e) {
            logger.error("查询用户失败", e);
            return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
        }
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC, Constants.INF_DESC_SUCC, imUser);
    }

    @RequestMapping(value = "/listByRoleId", method = {RequestMethod.GET})
    public String listImUsersByRoleId(@RequestParam(value = "roleid") Long roleId) {
        List<ImUserPo> imUserPoList;
        try {
            if (roleId != null) {
                imUserPoList = imUserService.listImUsersByRoleId(roleId);
            } else {
                return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, "缺少参数roleid");
            }
        } catch (Exception e) {
            logger.error("查询用户—角色失败", e);
            return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
        }
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC, Constants.INF_DESC_SUCC, imUserPoList);
    }

    @RequestMapping(value = "/listByOrgId", method = {RequestMethod.GET})
    public String listImUserByOrgId(@RequestParam(value = "orgid") Long orgId) {
        List<ImUserPo> imUserPoList;
        try {
            imUserPoList = imUserService.listImUserByOrgId(orgId);
        } catch (Exception e) {
            logger.error("查询用户—角色失败", e);
            return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
        }
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC, Constants.INF_DESC_SUCC, imUserPoList);
    }

    @RequestMapping(value = "/addRole", method = RequestMethod.POST)
    public String addImUserRoleRela(@RequestBody String reqParams) {
        if (logger.isDebugEnabled()) {
            logger.debug(reqParams);
        }
        try {
            Long userId = (Long) GsonUtils.toMap(reqParams).get("userId");
            Long roleId = (Long) GsonUtils.toMap(reqParams).get("roleId");
            if(userId != null && roleId != null){
                imUserService.addImUserRoleRela(userId, roleId);
            }else {
                return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR,"参数不对");
            }
        } catch (Exception e) {
            logger.error("新增用户-角色失败", e);
            return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
        }
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC, Constants.INF_DESC_SUCC, null);
    }

    @RequestMapping(value = "/deleteRole")
    public String deleteImUserRoleRela(@RequestBody String reqParams) {
        if (logger.isDebugEnabled()) {
            logger.debug(reqParams);
        }
        try {
            Long userId = (Long) GsonUtils.toMap(reqParams).get("userId");
            Long roleId = (Long) GsonUtils.toMap(reqParams).get("roleId");
            if(userId != null && roleId != null){
                imUserService.deleteImUserRoleRela(userId, roleId);
            } else {
                return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, "参数不对");
            }
        } catch (Exception e) {
            logger.error("删除用户-角色失败", e);
            return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
        }
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC, Constants.INF_DESC_SUCC, null);
    }

    @RequestMapping(value = "/listPrivilege")
    public String listImPrivilegeByUserId(@RequestParam(value = "userid") Long userId) {
        List<ImPrivilegePo> imPrivilegePoList;
        try {
            imPrivilegePoList = imUserService.listImPrivilegeByUserId(userId);
        } catch (Exception e) {
            logger.error("查询用户-权限失败", e);
            return ResponseUtils.feedback(Constants.INF_CODE_ERROR, Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
        }
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC, Constants.INF_DESC_SUCC, imPrivilegePoList);
    }
    
    /**
     * 用于登陆
     * @param userName
     */
    @RequestMapping(value = "/login")
    public String login(
	     HttpServletRequest req){
	
	  System.out.println(req.getMethod());
	        //获取项目名称
	        System.out.println(req.getContextPath());
	        //获取完整请求路径
	        System.out.println(req.getRequestURL());
	        //获取除了域名外的请求数据
	        System.out.println(req.getRequestURI());
	        //获取请求参数
	        System.out.println(req.getQueryString());
	        System.out.println("----------------------------------------------------------");
	        //获取请求头
	        String header = req.getHeader("user-Agent");
	        System.out.println(header);
	        header = header.toLowerCase();
	        //根据请求头数据判断浏览器类型
	        if(header.contains("chrome")){
	            System.out.println("您的访问浏览器为谷歌浏览器");
	        }else if(header.contains("msie")){
	            System.out.println("您的访问浏览器为IE浏览器");
	        }else if(header.contains("firefox")){
	            System.out.println("您的访问浏览器为火狐浏览器");
	        }else{
	            System.out.println("您的访问浏览器为其它浏览器");
	        }
	        System.out.println("----------------------------------------------------------");
	        //获取所有的消息头名称
	        Enumeration<String> headerNames = req.getHeaderNames();
	        //获取获取的消息头名称，获取对应的值，并输出
	        while(headerNames.hasMoreElements()){
	            String nextElement = headerNames.nextElement();
	            System.out.println(nextElement+":"+req.getHeader(nextElement));
	        }
	        System.out.println("----------------------------------------------------------");
	        //根据名称获取此重名的所有数据
	        Enumeration<String> headers = req.getHeaders("accept");
	        while (headers.hasMoreElements()) {
	            String string = (String) headers.nextElement();
	            System.out.println(string);
	        }
	logger.info("userName...."+req+"..login");
	Map<String,Object> map = new HashMap<String,Object>(); 
	map.put("name", "萌二");
	map.put("role", "the king of Q planet");
	return ResponseUtils.feedback(Constants.INF_CODE_SUCC, Constants.INF_DESC_SUCC, map);
    }
}
